<template>
  <u-navbar
      title=""
      :autoBack="true"
  >
    <template #center>
      <view class="sort-button"
            style="display: flex;align-items: center;
            justify-content: space-between;padding: 0 30rpx">
        <view style="display: flex;align-items: center">
          <image style="width: 25px;height: 25px;border-radius: 50%" :src="chatInfo.userInfo.avatar"></image>
          <text>&nbsp;{{ chatInfo.userInfo.userName }}</text>&nbsp;
        </view>
      </view>

    </template>
  </u-navbar>
  <view class="chat" style="padding-top: 80px ">
    <view
        :style="{height: `${windowHeight-inputHeight} rpx`}"
        id="scrollview"
        scroll-y
        :scroll-top="scrollTop"
        class="scroll-view"
    >
      <!--      <view style="position:fixed;">-->
      <!--        windowHeight: {{ windowHeight }}-->
      <!--        inputHeight: {{ inputHeight }}-->
      <!--        scrollTop: {{ scrollTop }}-->
      <!--      </view>-->

      <!-- 聊天主体 -->
      <view id="msglistview" class="chat-body">
        <!-- 聊天记录 -->
        <view v-for="(item,index) in chatInfo.chatList" :key="index">
          <!-- 自己发的消息 -->
          <view class="item self" v-if="item.fromUserId != userId">
            <!-- 文字内容 -->
            <view v-if="item.messageType == 'text'" class="content right">
              {{ item.content }}
            </view>
            <view v-else style="padding: 0;" class="content right">
              <navigator @tap="sendFileList1(index,item.content)" url="/pages/index/chatFullScreen">
                <image v-if="isImageUrl(item.content)"
                       class="file-item-multi"
                       lazy-load
                       mode="heightFix"
                       :src="item.content">
                  <template v-slot:loading>
                    <up-loading-icon></up-loading-icon>
                  </template>

                </image>
                <video v-if="isVideoUrl(item.content)"
                       object-fit="cover"
                       style="position: relative;"
                       :enable-progress-gesture="false"
                       :vslide-gesture-in-fullscreen="false"
                       :show-fullscreen-btn="false"
                       :show-center-play-btn="false"
                       :show-play-btn="false"
                       class="file-item-multi" :src="item.content">
                  <cover-image
                      class="play-btn"
                      src="https://www.douluodalu.icu:9000/school/static/play_white.png">
                  </cover-image>
                </video>
              </navigator>

            </view>
            <!-- 头像 -->
            <image class="avatar" :src="chatInfo.myInfo.avatar"></image>
          </view>
          <!-- 机器人发的消息 -->
          <view class="item Ai" v-if="item.fromUserId == userId">
            <!-- 头像 -->
            <image class="avatar" :src="chatInfo.userInfo.avatar"></image>
            <!-- 文字内容 -->
            <view v-if="item.messageType == 'text'" class="content left">
              {{ item.content }}
            </view>
            <view v-else style="padding: 0;margin-left: 15px" class="content left">
              <navigator @tap="sendFileList1(index,item.content)" url="/pages/index/chatFullScreen">
                <image v-if="isImageUrl(item.content)"
                       class="file-item-multi"
                       lazy-load
                       mode="heightFix"
                       :src="item.content">
                  <template v-slot:loading>
                    <up-loading-icon></up-loading-icon>
                  </template>

                </image>
                <video v-if="isVideoUrl(item.content)"
                       object-fit="cover"
                       style="position: relative;"
                       :enable-progress-gesture="false"
                       :vslide-gesture-in-fullscreen="false"
                       :show-fullscreen-btn="false"
                       :show-center-play-btn="false"
                       :show-play-btn="false"
                       class="file-item-multi" :src="item.content">
                  <cover-image
                      class="play-btn"
                      src="https://www.douluodalu.icu:9000/school/static/play_white.png">
                  </cover-image>
                </video>
              </navigator>

            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部消息发送栏 -->
    <!-- 用来占位，防止聊天消息被发送框遮挡 -->
    <view class="chat-bottom" :style="{height: `${inputHeight}px`}">
      <view class="send-msg" :style="{bottom:`${keyboardHeight + 0.1}px`}">
        <scroll-view v-if="fileList1" :scroll-x="true" scroll-with-animation>
          <view class="bottom-media-list">
            <view v-for="(item, index) in fileList1"
                  @tap.stop="sendFileList2(index)"
                  style="position: relative"
                  class="bottom-media-list-item" :key="index">
              <navigator url="/pages/index/fileFullScreen">
                <image v-if="isImageUrl(item)"
                       class="bottom-media-list-item-image"
                       mode="widthFix"
                       :src="item">
                </image>
                <video
                    v-if="isVideoUrl(item)"
                    :enable-progress-gesture="false"
                    :vslide-gesture-in-fullscreen="false"
                    :show-fullscreen-btn="false"
                    :show-center-play-btn="false"
                    :show-play-btn="false"
                    object-fit="contain"
                    class="bottom-media-list-item-image" :src="item">+
                </video>
                <view @tap.stop="deletePic(index)" class="close-images">
                  <u-icon color="#fa4358"
                          name="close-circle-fill">
                  </u-icon>
                </view>

              </navigator>
            </view>
          </view>
        </scroll-view>
<!--        :disabled="enableText"-->
<!--        v-if="!enableText"-->
        <view class="uni-textarea">
					<textarea v-model="schoolChatMessage.content"
                    maxlength="-1"
                    ref="messageInput"
                    style="max-height: 13vh;height: 36px!important;"
                    adjust-position

                    placeholder="良言一句三冬暖"
                    confirm-type="send"
                    :focus="textareaFocus"
                    :show-confirm-bar="false"
                    :adjust-position="false"
                    @linechange="sendHeight"
                    @focus="focus" @blur="blur"
                    auto-height></textarea>
<!--          <view v-else style="max-height: 13vh;height: 36px!important;-->
<!--  border-radius: inherit;-->
<!--  padding: 8px 0 8px 12px;-->
<!--  margin-left: 5px;-->
<!--  max-height: 12vh;-->
<!--  width: 65vw;-->
<!--  font-size: 18px;-->
<!--  color: #333333;">-->

<!--          </view>-->
          <view style="display: flex;align-items: center;  background-color: #e6e6e6;">
            <image @tap="getMedia(bottomList.type)"
                   style="padding: 0.5rem;width: 1.7rem;height: 1.7rem;"
                   :src="emojiAndKeyboardUrl"
                   border="none">
            </image>
            <text v-if="schoolChatMessage.content || fileList1.length === 1"
                  style="color: white;background-color: #4ea4f9;border-radius: 72rpx;padding: 5px 10px"
                  @click="handleSend">发送
            </text>
            <image @tap="getMedia(bottomList2.type)"
                   v-else
                   style="padding: 0.5rem;width: 1.7rem;height: 1.7rem;"
                   :src="bottomList2.url"
                   border="none">
            </image>
          </view>
        </view>
      </view>
    </view>
    <u-popup @close="emojiClose"
             mode="bottom"
             overlay-opacity="0"
             :show="isEmojiPanelShown">
      <scroll-view scroll-y :style="{ height: emojiHeight   +'px' }">
        <view class="emoj-wrapper">
          <view class="emoj" v-for="(emoji, index) in emojis" :key="index" @tap="insertEmoji(emoji)">
            {{ emoji }}
          </view>
        </view>
      </scroll-view>

    </u-popup>

  </view>
</template>
<script>
import {getToken, getUserId} from "@/utils/auth";
import {getChatInfo, readMessage} from "@/api/chat";
import {getDateTime, isImageUrl, isVideoUrl} from "@/utils/format";
import {deletePic} from "@/api/comment";
import AllTopic from "@/pages/topic/AllTopic.vue";
import useUserStore from "@/store/user";
import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram';

export default {
  components: {AllTopic},
  data() {
    return {
      enableText: false,
      textareaFocus: false,
      isEmojiPanelShown: false,
      emojis: [
        '😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎', '😍', '😘', '😗', '😙', '😚',
        '☺️', '🙂', '🤗', '🤩', '🤔', '🤨', '😐', '😑', '😶', '🙄', '😏', '😣', '😥', '😮', '🤐', '😯', '😪', '😫', '😴', '😌',
        '😛', '😜', '😝', '🤤', '😒', '😓', '😔', '😕', '🙃', '🤑', '😲', '☹️', '🙁', '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧', '😨',
        '😩', '🤯', '😬', '😰', '😱', '😳', '🤪', '😵', '👻', '👽', '🤖', '💩', '😺', '😸', '😹', '😻', '😼', '😽', '🙀', '😿', '😾'
      ],

      messagesRead: 0,
      bottomList: {
        url: 'https://www.douluodalu.icu:9000/school/static/post_emoj.png',
        type: 4
      }
      ,
      bottomList2: {
        url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
        type: 1
      },
      tempFilePaths: [],
      fileList1: [],
      //键盘高度
      keyboardHeight: 0,
      //底部消息发送高度
      bottomHeight: 0,
      tempHeight: 0,
      emojiHeight: 0,
      //滚动距离
      scrollTop: 0,
      userId: '',
      //发送的消息
      schoolChatMessage: {
        content: "",
        messageType: "text"
      },
      schoolChatMessageForm: {},
      chatInfo: {
        chatList: {},
        myInfo: {},
        userInfo: {}
      },
    }
  },
  mounted() {

  },
  updated() {
    //页面更新时调用聊天消息定位到最底部
    this.scrollToBottom();
  },
  computed: {
    windowHeight() {
      return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
    },
    // 键盘弹起来的高度+发送框高度
    inputHeight() {
      return this.bottomHeight + (this.isEmojiPanelShown ? this.emojiHeight : this.keyboardHeight)
    },
    emojiAndKeyboardUrl() {
      return this.isEmojiPanelShown ? 'http://www.douluodalu.icu:9000/school/static/keyboard.png' : 'https://www.douluodalu.icu:9000/school/static/post_emoj.png'
    }

  },
  onLoad(options) {
    let token = getToken();
    if(token !== null && token !== ''&& token !== undefined){
      this.getChatList(options.userId)
      readMessage(options.userId, getUserId()).then(res => {
        let number = Number(useUserStore().unreadMessageNumber)
        number = number - Number(res.data)
        useUserStore().setUnreadMessageNumber(number)
      })
      this.userId = options.userId
      // this.socket()
      uni.onKeyboardHeightChange(res => {
        if (this.isEmojiPanelShown) {
          this.keyboardHeight = this.emojiHeight;
        } else {
          this.keyboardHeight = res.height - 1
          if (this.keyboardHeight < 0) this.keyboardHeight = 0;
          if (this.keyboardHeight > 0) this.emojiHeight = this.keyboardHeight;
          if (this.keyboardHeight > 0) this.tempHeight = this.keyboardHeight;
        }
        this.scrollToBottom()
      })
    }else {
      uni.navigateTo({
        url: '/pages/my/login',
      })
    }

  },
  onUnload(options) {
    uni.offKeyboardHeightChange()
    this.websocketclose()
    // uni.$off('websocketMessage')
  },
  onShow() {
    // 接收websocket消息及处理
    uni.$on('websocketMessage', (res) => {
      console.log(res)
      if (res  != null) {
        let receivedData = JSON.parse(res)
        if(receivedData?.fromUserId !== undefined){
          let receivedMessage = {
            content: receivedData.content,
            readStatus: receivedData.readStatus,
            fromUserId: receivedData.fromUserId,
            toUserId: receivedData.toUserId,
            messageType: receivedData.messageType,
            id: receivedData.id,
            sendTime: receivedData.sendTime,
          }
          this.chatInfo.chatList.push(receivedMessage);
          this.readMessage(receivedMessage.fromUserId, receivedMessage.toUserId)
        }

      }
      // this.textareaFocus = true

      console.log(res)
    })
    let token = getToken();
    if(token !== null && token !== ''&& token !== undefined){

    }else {
      uni.navigateTo({
        url: '/pages/my/login',
      })
    }


  },
  methods: {

// 获取指定选择器元素的高度
    getHeight(classNa) {
      setTimeout(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select(classNa).boundingClientRect(data => {
          this.$emit('heightChange', data.height);
        }).exec();
      }, 10);
    },
    emojiClose() {
      this.isEmojiPanelShown = false;
      this.textareaFocus = true
      this.scrollToBottom()
    },
    insertEmoji(emoji) {
      this.schoolChatMessage.content += emoji; // 将emoji添加到输入框中
    },
    async readMessage(fromUserId, toUserId) {
      const res = await readMessage(fromUserId, toUserId)

      this.messagesRead = res.data
    },
    isVideoUrl,
    isImageUrl,
    async getChatList(userId) {
      const {data: res} = await getChatInfo(userId)
      this.chatInfo = res
    },
    sendFileList1(currentIndex, url) {
      setTimeout(() => {
        uni.$emit('sendFileList', {
          fileList: [url],
          currentIndex: currentIndex
        })
      }, 500)
    },
    sendFileList2(currentIndex) {
      setTimeout(() => {
        uni.$emit('sendFileList', {
          fileList: this.fileList1,
          currentIndex: currentIndex
        })
      }, 500)

    },
    async deletePic(index) {
      this.fileList1.splice(index, 1)
      this.schoolChatMessage.content = ""
      this.schoolChatMessage.messageType = "text"
      // this.enableText = false
      await deletePic(this.fileList1[index])
    },
// 新增图片
    uploadFile(tempFilePaths) {
      uni.uploadFile({
        url: this.$BASE_UPLOAD, //仅为示例，非真实的接口地址
        filePath: tempFilePaths,
        // filePath: tempFilePaths[i],
        name: 'file',
        header: {
          'Authorization': getToken(),
        },
        success: (uploadFileRes) => {
          let res = (JSON.parse(uploadFileRes.data)).data.url
          if (isVideoUrl(res)) {
            this.schoolChatMessage.messageType = 'video'
          }
          if (isImageUrl(res)) {
            this.schoolChatMessage.messageType = 'image'
          }
          this.schoolChatMessage.content = res
          this.sendPic(res)
          // this.fileList1.push(res)
        }
      })
    },
    // 给后端发消息时调用
    sendMsg(msg) {
      // try {
        useUserStore().socketTask.socketTask.send({
          data: msg
        });
      // } catch (e) {
      //   uni.connectSocket({
      //     url: this.$CHAT_URL.replace("https://", "wss://")
      //         .replace("http://", "ws://") + "/websocket/" + getUserId(),
      //     success: () => {
      //       console.log('WebSocket连接成功');
      //     },
      //     fail: (err) => {
      //       console.error('WebSocket连接失败', err);
      //     },
      //   });
      //   uni.sendSocketMessage({
      //     data: msg
      //   });
      //   console.log(e)
      // }
    },
    getMedia(type) {
      let _this = this
      if (type === 1 || type === 2) {
        // this.enableText = true
        this.$authorize('camera', false, true).then(() => {
          //成功授权后相应逻辑
          if (type === 1) {
            uni.chooseMedia({
              count: 1,
              mediaType: ['image'],
              //可以指定是原图还是压缩图，默认二者都有
              sourceType: ['camera', 'album'], //从相册选择
              success: res => {
                res.tempFiles.forEach(item => {
                  _this.uploadFile(item.tempFilePath)
                })
              }
            });
          }
          if (type === 2) {
            uni.chooseMedia({
              count: 9 - this.fileList1.length,
              mediaType: ['video'],
              sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
              sourceType: ['camera', 'album'], //从相册选择
              success: function (res) {
                res.tempFiles.forEach(item => {
                  _this.uploadFile(item.tempFilePath)
                })
                if (_this.fileList1.length > 9) {
                  _this.fileList1.splice(9, _this.fileList1.length - 9);
                  uni.showToast({
                    title: '最多选择九个哦',
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            });
          }
        }).catch(() => {
          uni.showToast({title: '请先授权相机权限'})
        }).finally(() => {
          //无论授权成功或者失败都执行的逻辑
        });
      }
      if (type === 4) {
        this.textareaFocus = false
        this.keyboardHeight = this.emojiHeight
        if (this.isEmojiPanelShown) {
          this.isEmojiPanelShown = false
          this.emojiHeight = 0
          this.textareaFocus = true
        } else {
          this.isEmojiPanelShown = true
          this.emojiHeight = this.tempHeight
          this.keyboardHeight = this.tempHeight
        }
      }
      this.scrollToBottom()
    },
    focus() {
      if (this.isEmojiPanelShown) {
        this.keyboardHeight = this.emojiHeight;
      }
      this.scrollToBottom()
    },
    blur() {
      this.isEmojiPanelShown = false
      this.textareaFocus = false
      this.keyboardHeight = 0;
      this.emojiHeight = 0
      this.scrollToBottom()
    },
    sendPic(url) {
      //如果消息不为空
        // 先复制一份schoolChatMessageForm，以避免后续操作影响已发送的消息内容
        const form = {...this.schoolChatMessage};
        this.schoolChatMessage.toUserId = this.userId;
        this.schoolChatMessage.fromUserId = getUserId();
        this.schoolChatMessage.sendTime = getDateTime();
        this.schoolChatMessage.content = url;
        this.schoolChatMessage.messageType = url;

// 确保form也包含正确的属性值
        form.toUserId = this.userId;
        form.fromUserId = getUserId();
        form.sendTime = getDateTime();

        this.sendMsg(JSON.stringify(form));
        this.chatInfo.chatList.push(form);


// 在这里清空内容
        this.schoolChatMessage.content = "";
        this.fileList1 = [];
        this.schoolChatMessage.messageType = "text";
        this.scrollToBottom();
    },

    handleSend() {
      //如果消息不为空
      if (!this.schoolChatMessage.content || !/^\s+$/.test(this.schoolChatMessage.content)) {
        // 先复制一份schoolChatMessageForm，以避免后续操作影响已发送的消息内容
        const form = {...this.schoolChatMessage};
        this.schoolChatMessage.toUserId = this.userId;
        this.schoolChatMessage.fromUserId = getUserId();
        this.schoolChatMessage.sendTime = getDateTime();

// 确保form也包含正确的属性值
        form.toUserId = this.userId;
        form.fromUserId = getUserId();
        form.sendTime = getDateTime();

        this.sendMsg(JSON.stringify(form));
        this.chatInfo.chatList.push(form);


// 在这里清空内容
        this.schoolChatMessage.content = "";
        this.fileList1 = [];
        this.schoolChatMessage.messageType = "text";
        this.enableText = false
        this.scrollToBottom();

      } else {
        uni.showToast({title: '不能发送空白消息'})
      }

    },
    // 关闭连接时调用
    websocketclose() {
      uni.onSocketClose(function (res) {
        console.log('WebSocket 已关闭！');
      });
    },

    // px转换成rpx
    rpxTopx(px) {
      let deviceWidth = wx.getSystemInfoSync().windowWidth
      let rpx = (750 / deviceWidth) * Number(px)
      return Math.floor(rpx)
    },
    // 监视聊天发送栏高度
    sendHeight() {
      setTimeout(() => {
        let query = uni.createSelectorQuery();
        query.select('.send-msg').boundingClientRect()
        query.exec(res => {
          this.bottomHeight = this.rpxTopx(res[0].height)
        })
      }, 10)
    },
    // 滚动至聊天底部
    scrollToBottom(e) {
      this.$nextTick(() => {
        uni.pageScrollTo({
          scrollTop: 2000000,
          duration: 0
        });
      });
      // setTimeout(() => {
      //   let query = uni.createSelectorQuery().in(this);
      //   query.select('#scrollview').boundingClientRect();
      //   query.select('#msglistview').boundingClientRect();
      //   query.exec((res) => {
      //     if (res[1].height > res[0].height) {
      //       this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
      //     }
      //   })
      // }, 15)
    },
    // 发送消息
  }
}
</script>
<style lang="scss" scoped>
.bottom-media-list {
  display: flex;
  align-items: center;
  margin: 0 30rpx;
  width: max-content;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  box-shadow: 0 0 10px 0px #b7b4b4;
}

.bottom-media-list-item {
  padding: 5px;
}

.bottom-media-list-item-image {
  width: 128rpx;
  height: 128rpx;
  z-index: 99
}

.close-images {
  z-index: 999;
  position: relative;
  left: 3.9rem;
  top: -5.0rem;
  background-color: white;
  border-radius: 50%;
  width: max-content;
  height: max-content;
}

.textarea-model-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 30rpx;

}

.file-item-multi {
  border-radius: 12rpx;
  max-height: 200px;
  max-width: 200px;
}

.play-btn {
  width: 30px;
  height: 30px;
  top: 35%;
  left: 35%;
  position: absolute
}

$chatContentbgc: rgba(138, 138, 138, 0.15);
$sendBtnbgc: #4F7DF5;

view, button, text, input {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 聊天消息 */
.chat {
  height: 100%;
  background-color: #F1F1F1;

  .scroll-view {
    padding-left: 20rpx;
    padding-right: 20rpx;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 150rpx;
    background-color: #F1F1F1;

    ::-webkit-scrollbar {
      display: none;
      width: 0 !important;
      height: 0 !important;
      -webkit-appearance: none;
      background: transparent;
      color: transparent;
    }

    // background-color: orange;
    background-color: #fff;

    .chat-body {
      display: flex;
      flex-direction: column;
      padding-top: 23rpx;
      // background-color:skyblue;

      .self {
        justify-content: flex-end;
      }

      .item {
        display: flex;
        padding: 23rpx 30rpx;
        // background-color: greenyellow;

        .right {
          background-color: $chatContentbgc;
        }

        .left {
          background-color: $chatContentbgc;
        }

        .content {
          position: relative;
          max-width: 486rpx;
          border-radius: 15rpx;
          word-wrap: break-word;
          padding: 12rpx 24rpx;
          margin: 0 24rpx;
          font-size: 32rpx;
          font-weight: 500;
          color: #333333;
          line-height: 42rpx;
        }

        .avatar {
          width: 78rpx;
          height: 78rpx;
          border-radius: 50%;
          overflow: hidden;


        }
      }
    }
  }

  /* 底部聊天发送栏 */
  .chat-bottom {
    width: 100%;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 30rpx 30rpx 0 19rpx;
    height: 200rpx;


    .send-msg {
      position: fixed;

      bottom: 0;
      background-color: #fff;
      padding-bottom: 15rpx;
      padding-right: 30rpx;
      transition: all 0.1s ease;
    }

    .uni-textarea {
      border-radius: 50rpx;
      width: 95vw;
      background-color: #e6e6e6;
      display: flex;
      align-items: center;

    }

    .send-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 70rpx;
      margin-left: 25rpx;
      width: 128rpx;
      height: 75rpx;
      background: $sendBtnbgc;
      font-size: 28rpx;
      font-weight: 500;
      color: #FFFFFF;
      line-height: 28rpx;
    }
  }

}

textarea {
  background-color: #e6e6e6;
  border-radius: inherit;
  padding: 8px 0 8px 12px;
  margin-left: 5px;
  max-height: 12vh;
  width: 65vw;
  font-size: 18px;
  color: #333333;
}

.emoj-wrapper {
  display: flex;
  flex-wrap: wrap;
}

.emoj {
  font-size: 30px;
  margin: 6px;
}
</style>
